package com.ruoyi.web.controller.example;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.resturant.domain.ResBanner;
import com.ruoyi.resturant.service.IResBannerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Anonymous
@RestController
@RequestMapping("/api/Bannerredis")
@Api(tags="BannerRedis测试")
public class RedisResBannerController {
    @Autowired
    private IResBannerService resBannerService;          //声明轮播图service
    @Autowired
    private RedisCache redisCache;

    /**
     * 根据轮播图ID查询轮播图详情，并把轮播图信息存入Redis中
     * @param id 轮播图ID
     * @return
     */
    @ApiOperation("根据轮播图ID查询轮播图详情，并把轮播图信息存入Redis中")
    @ApiImplicitParam(name = "id", value = "轮播图ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public AjaxResult setRedisObj(@PathVariable("id") Long id){
        ResBanner resBanner=resBannerService.selectResBannerById(id);

        String str= JSON.toJSONString(resBanner);

        redisCache.setCacheObject(String.valueOf(id),str,1, TimeUnit.DAYS);

        return AjaxResult.success(resBanner);
    }

    /**
     * 根据轮播图ID从Redis取轮播图的详情
     * @param id
     * @return
     */
    @ApiOperation("根据轮播图ID从redis中查询轮播图详情")
    @ApiImplicitParam(name = "id", value = "轮播图ID",
            required = true, dataType = "long", paramType = "path",
            dataTypeClass = Long.class)
    @GetMapping("/ids/{id}")
    public AjaxResult getRedisObj(@PathVariable("id")Long id){
        //1 根据轮播图ID从redis取得轮播图详情的json字符串
        String str= redisCache.getCacheObject(String.valueOf(id));
        //2 把轮播图详情的json字符串转换为一个人model对象ResBanner
        ResBanner resBanner= JSON.parseObject(str,ResBanner.class);

        if (resBanner==null){
            resBanner=resBannerService.selectResBannerById(id);

            String strDB= JSON.toJSONString(resBanner);

            redisCache.setCacheObject(String.valueOf(id),strDB,1, TimeUnit.DAYS);

        }
        //3 返回取得model对象
        return AjaxResult.success(resBanner);

    }
}
